package org.nanhill.gecko;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author alin [xalinx at gmail dot com]
 * @date 2006-12-4
 */
public class TextSpider {
	private final static Log logger = LogFactory.getLog(TextSpider.class);

	private final static String ARG_RESUME = "-resume";

	private final static String DEF_CONFIG_FILE = "spider.properties";

	public static void main(String[] args) {
		if (args.length > 2) {
			usage();
			System.exit(0);
		}
		String configPath = null;
		boolean resume = false;
		if (args.length == 0) {
			configPath = DEF_CONFIG_FILE;
			// search config file in first location
			File configFile = new File(configPath);
			if (configFile.exists()) {
				configPath = configFile.getAbsolutePath();
			} else {
				// search config file in second location
				URL classpathConfig = TextSpider.class.getResource("/"
						+ configPath);
				if (null == classpathConfig) {
					logger
							.error("Package imcomplete, config file not found in root classpath");
					System.exit(1);
				}
				configPath = classpathConfig.getFile();
			}
		} else if (args.length == 1) {
			configPath = args[0];
		} else if (!args[0].equals(ARG_RESUME)) {
			usage();
			System.exit(0);
		} else {
			resume = true;
			configPath = args[1];
		}

		Properties props = null;
		try {
			FileInputStream propsIn = new FileInputStream(configPath);
			props = new Properties();
			props.load(propsIn);
			propsIn.close();
		} catch (FileNotFoundException fnfe) {
			logger.error("File not found: " + args[0], fnfe);
			System.exit(1);
		} catch (IOException ioe) {
			logger.error("IO Exception caught reading config file: "
					+ ioe.getMessage(), ioe);
			System.exit(1);
		}

		logger.debug("Configuring Spider from properties...");
		SpiderConfig config = new SpiderConfig(props);
		logger.debug(config);
		Spider spider = new Spider(config);

		if (resume) {
			logger.info("Reading checkpoint...");
			spider.readCheckpoint();
		}

		logger.info("Starting Spider...");
		spider.start();

		System.out.println("\nHit any key to stop Spider\n");
		try {
			while (spider.isRunning()) {
				if (System.in.available() != 0) {
					System.out.println("\nStopping Spider...\n");
					spider.stop();
					break;
				}
				pause(config.getSpiderStopPause());
			}
		} catch (IOException ioe) {
			logger.error("Unexpected io exception caught: " + ioe.getMessage(),
					ioe);
			System.exit(1);
		}
	}

	private static void pause(long howLong) {
		try {
			Thread.sleep(howLong);
		} catch (InterruptedException ignored) {
		}
	}

	private static void usage() {
		System.out.println("Usage: weblech.ui.TextSpider [" + ARG_RESUME
				+ "] [config file]");
	}

}